"use client";
import { ChangeEvent, FC, PropsWithChildren, useMemo, useState } from "react";
import clsx from "clsx";
import Link from "next/link";
import ButtonOwn from "@/components/ButtonOwn";
import "./style.scss";

/**
 * @description 登录注册From表单
 * @param {string} type 使用类型
 * @param {(params: any) => void} callbackFun 回调方法
 */
export interface FromComProps {
    type?: string;
    text?: string;
    callbackFun?: (params: any) => void;
}

const FromCom: FC<PropsWithChildren<FromComProps>> = ({type = 'login', callbackFun}) => {
    let [pwdVisible, setPwdVisible] = useState(false)
    const spanClassName = clsx("iconfont", {
        "icon-kejian": pwdVisible,
        "icon-bukejian": !pwdVisible,
    });

    let [fromParam, setFromParam] = useState({
        userPhone: '',
        pwd: ''
    })

    const activeCls = useMemo(() => {
        let { userPhone, pwd } = fromParam
        if (userPhone && userPhone.length==11 && pwd && pwd.length>6) {
            return true
        }
        return false
    }, [fromParam]);


    const setInputVal = (e: ChangeEvent<HTMLInputElement>, propsName: string) => {
        setFromParam({
            ...fromParam,
            [propsName]: e.target.value
        })
    }

    const verifyPwd = (e: any) => {
        let pwd = e.target.value || '';
        pwd.replaceAll(/[^a-zA-Z0-9_-]/g, '')
        setFromParam({ ...fromParam, pwd })
        console.log('fromParam', fromParam.pwd)
    }

    const submitRequest = () => {
        activeCls && callbackFun!(fromParam)
    }

    return (
        <div className="FromCom">
            <div className="phoneInput">
                <span className="after">+55</span>
                <input type="tel" value={fromParam.userPhone} onChange={(e) => setInputVal(e, 'userPhone') } placeholder="Número de Celular" maxLength={11} />
            </div>
            <div className="passwordInput">
                <input type={pwdVisible?'text':'password'} value={fromParam.pwd} onChange={(e) => setInputVal(e, 'pwd') } onInput={verifyPwd} placeholder="Senha" maxLength={12}/>
                <span className={spanClassName} onClick={() => setPwdVisible(!pwdVisible)}></span>
            </div>
            <div className="btnContent">
                <div className="tips"> O número de telefone não existe. </div>
                <ButtonOwn active={activeCls} callbackFun={submitRequest}>{type == 'login'? 'Login' : 'Criar conta'}</ButtonOwn>
            </div>
            <div className="link">
                {
                    type == 'login' ? (
                        <>
                            <Link href="/br/resetPhone">Esqueci minha senha?</Link>
                            <Link href="/br/register">Criar Conta Nova</Link>
                        </>
                    ) : <Link href="/br/login" className="active" replace>Já tem uma conta? Log in</Link>
                }     
            </div>
        </div>
    );
};

export default FromCom;
